package labox.innovation.gameserver.util;

import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.gameserver.GameTimeController;
import labox.innovation.gameserver.model.Punish;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

/**
 * Flood protector implementation.
 * 
 * @author fordfrog
 */
public final class FloodProtectorAction {

	/**
	 * Logger
	 */
	private static final Logger _log = LoggerFactory.getLogger(FloodProtectorAction.class.getName());

	/**
	 * Player for this instance of flood protector.
	 */
	private final FuzePcInstance _player;

	/**
	 * Configuration of this instance of flood protector.
	 */
	private final FloodProtectorConfig _config;

	/**
	 * Next game tick when new request is allowed.
	 */
	private volatile int _nextGameTick = GameTimeController.getGameTicks();

	/**
	 * Request counter.
	 */
	private AtomicInteger _count = new AtomicInteger(0);

	/**
	 * Flag determining whether exceeding request has been logged.
	 */
	private boolean _logged;

	/**
	 * Flag determining whether punishment application is in progress so that we do not apply punisment multiple times (flooding).
	 */
	private volatile boolean _punishmentInProgress;

	/**
	 * Creates new instance of FloodProtectorAction.
	 * 
	 * @param player
	 *            player for which flood protection is being created
	 * @param config
	 *            flood protector configuration
	 */
	public FloodProtectorAction(final FuzePcInstance player, final FloodProtectorConfig config) {
		super();
		_player = player;
		_config = config;
	}

	/**
	 * Checks whether the request is flood protected or not.
	 * 
	 * @param command
	 *            command issued or short command description
	 * 
	 * @return true if action is allowed, otherwise false
	 */
	public boolean tryPerformAction(final String command) {
		final int curTick = GameTimeController.getGameTicks();

		if (curTick < _nextGameTick || _punishmentInProgress) {
			if (_config.LOG_FLOODING) {
				_log.warn(StringUtil.concat(_config.FLOOD_PROTECTOR_TYPE, ": Player [", _player.getName(), "] called command [", command, "] [~", String.valueOf((_config.FLOOD_PROTECTION_INTERVAL - (_nextGameTick - curTick)) * GameTimeController.MILLIS_IN_TICK), " ms] after previous command"));
				_logged = true;
			}

			_count.incrementAndGet();

			if (!_punishmentInProgress && _config.PUNISHMENT_LIMIT > 0 && _count.get() > _config.PUNISHMENT_LIMIT && _config.PUNISHMENT_TYPE != null) {
				_punishmentInProgress = true;

				if ("kick".equals(_config.PUNISHMENT_TYPE)) {
					kickPlayer();
				} else if ("ban".equals(_config.PUNISHMENT_TYPE)) {
					banAccount();
				} else if ("jail".equals(_config.PUNISHMENT_TYPE)) {
					jailChar();
				}

				_punishmentInProgress = false;
			}

			return false;
		}

		if (_count.get() > 0) {
			if (_config.LOG_FLOODING) {
				_log.warn(StringUtil.concat(_config.FLOOD_PROTECTOR_TYPE, ": Player [", _player.getName(), "] issued [", String.valueOf(_count), "] extra requests within [~", String.valueOf(_config.FLOOD_PROTECTION_INTERVAL * GameTimeController.MILLIS_IN_TICK), " ms]"));
			}
		}

		_nextGameTick = curTick + _config.FLOOD_PROTECTION_INTERVAL;
		_logged = false;
		_count.set(0);

		return true;
	}

	/**
	 * Kick player from game (close network connection).
	 */
	private void kickPlayer() {
		_player.closeNetConnection();

		_log.warn(StringUtil.concat(_config.FLOOD_PROTECTOR_TYPE, ": Account [", _player.getAccountName(), "] kicked for flooding [char ", _player.getName(), "]"));

	}

	/**
	 * Bans char account and logs out the char.
	 */
	private void banAccount() {
		_player.getPunish().setPunishLevel(Punish.PunishLevel.ACC, _config.PUNISHMENT_TIME);
		_log.warn(StringUtil.concat(_config.FLOOD_PROTECTOR_TYPE, ": Account [", _player.getAccountName(), "] banned for flooding [char ", _player.getName(), "] ", _config.PUNISHMENT_TIME <= 0 ? "forever" : "for " + _config.PUNISHMENT_TIME + " mins"));
		_player.logout(false);
	}

	/**
	 * Jails char.
	 */
	private void jailChar() {
		_player.getPunish().setPunishLevel(Punish.PunishLevel.JAIL, _config.PUNISHMENT_TIME);
		_log.warn(StringUtil.concat(_config.FLOOD_PROTECTOR_TYPE, ": Player [", _player.getName(), "] jailed for flooding [char ", _player.getName(), "] ", _config.PUNISHMENT_TIME <= 0 ? "forever" : "for " + _config.PUNISHMENT_TIME + " mins"));
	}
}